package LC08;

import java.util.*;

/**
 * 735. 小行星碰撞
 *
 * @author zhangsan
 */
public class LC0735 {

    public static void main(String[] args) {
        int[] ints = asteroidCollision(new int[]{1,-2,-2,-2});
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }

    public static int[] asteroidCollision(int[] asteroids) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < asteroids.length; i++) {
            int ast = asteroids[i];
            if (ast < 0) {
                li(list, ast);
            } else {
                list.add(ast);
            }
        }

        ArrayList<Integer> list2 = new ArrayList<>();

        if (list.size() > 0) {
            for (int i = list.size() - 1; i >= 0; i--) {
                if (list.get(i) > 0) {
                    ri(list2, list.get(i));
                } else {
                    list2.add(list.get(i));
                }
            }
        }


        int[] ints = new int[list2.size()];
        for (int i = list2.size() - 1; i >= 0; i--) {
            ints[list2.size() - i - 1] = list2.get(i);
        }

        return ints;
    }

    public static void li(List<Integer> list, int ast) {
        if (list.size() == 0) {
            list.add(ast);
            return;
        }
        int size = list.size();
        for (int i = size - 1; i >= 0; i--) {
            Integer b = list.get(i);
            if (b < 0) {
                list.add(ast);
                break;
            } else {
                if (b > Math.abs(ast)) {
                    break;
                } else if (b == Math.abs(ast)) {
                    list.remove(i);
                    break;
                } else {
                    list.remove(i);
                    if (list.size() == 0) {
                        list.add(ast);
                        break;
                    }
                }
            }
        }
    }

    public static void ri(List<Integer> list, int ast) {
        int size = list.size();
        if (size == 0) {
            list.add(ast);
            return;
        }
        for (int i = size - 1; i >= 0; i--) {
            Integer b = list.get(i);
            if (b > 0) {
                list.add(ast);
                break;
            } else {
                if (b > Math.abs(ast)) {
                    break;
                } else if (b == Math.abs(ast)) {
                    list.remove(i);
                    break;
                } else {
                    list.remove(i);
                    if (list.size() == 0) {
                        list.add(ast);
                        break;
                    }
                }
            }
        }
    }
}
